const rp = require('request-promise-native');
const {resolve}=require('path');
const { appID, appsecret } = require('../config');
const { writeFile, readFile,exists } = require('fs');
const menu=require('./menu');
class Wechat {

    constructor() {

    }
    /**
     * 获取accessToken
     */
    getAccessToken() {
        const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appsecret}`;
        return new Promise((resolve, reject) => {
            rp({ method: 'GET', url, json: true }).then(res => {
                res.expires_in = Date.now() + (res.expires_in - 300) * 1000;
                resolve(res);
            }).catch(err => {
                reject('getAccessToken 出错' + err);
            })
        });


    }
    /**
     * 读取accesstoken
     */
    readAccessToken() {
        const path=resolve(__dirname,'access_token.txt');
        return new Promise((resolve, reject) => {
            readFile(path, { encoding: 'utf-8' }, (err, data) => {
                if (!err) {
                    resolve(JSON.parse(data));
                } else {
                    reject('readAccessToken 出错' + err);
                }
            });
        });

    }
    /**
     * 验证accesstoken 是否过期
     * @param {*} access_token 
     */
    valiadateAccessToken(access_token) {
        if (access_token && access_token.expires_in) {
            const expires_in = access_token.expires_in;
            return Date.now() > expires_in;
        } else {
            return true;
        }
    }
    /**
     * 保存accesstoken
     * @param {*} access_token 
     */
    saveAccessToken(access_token) {
        const path=resolve(__dirname,'access_token.txt');
        return new Promise((resolve, reject) => {
            access_token = JSON.stringify(access_token);
            writeFile(path, access_token, err => {
                if (!err) {
                    console.log('保存文件成功');
                    resolve();
                } else {
                    reject('保存文件出错' + err);
                }
            })
        });

    }
    freshAccessToken(){
      return  new Promise(async (resolve, reject) => {
            exists('./access_token.txt',async err=>{
                //过期或有问题不存在,重新请求
                if(!err){ 
                    let resToken = await this.getAccessToken();
                    await this.saveAccessToken(resToken);
                    resolve(resToken.access_token);
                }else{
                    this.readAccessToken().then(async res => {
                        if (!this.valiadateAccessToken(res)) {
                            resolve(res.access_token);
                        } else {
                            let resToken = await this.getAccessToken();
                            await this.saveAccessToken(resToken);
                            resolve(resToken.access_token);
                        }
                    }).catch(err => {
                        reject('读取文件出错' + err);
                    })
        
                }
            });
     
        });
    }
    createMenu(menu){
        return new Promise(async(resolve, reject) => {
            const token=await this.freshAccessToken();
            let url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
            rp({ method: 'POST', url, json: true ,body:menu}).then(res => {
                resolve(res);
            }).catch(err => {
                reject('createMenu 出错' + err);
            })
        });
    }
    deleteMenu(){
        return new Promise(async(resolve, reject) => {
            const token=await this.freshAccessToken();
            console.log(token);
            let url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+token;
            rp({ method: 'POST', url, json: true}).then(res => {
                resolve(res);
            }).catch(err => {
                reject('deleteMenu 出错' + err);
            })
        });
    }
    getJsTicket(){
        const path=resolve(__dirname,'js-ticket.txt');
        return new Promise(async(resolve, reject) => {
         await   readFile(path, { encoding: 'utf-8' }, async(err, data) => {
                if (!err) {
                    const tt=(JSON.parse(data));
                    // console.log(tt,Date.now())
                    if(Date.now() >tt.expires_in){
                        const token= await this.freshAccessToken();
                        let url=`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`;
                        let data =await rp({ method: 'GET', url, json: true});
                        data.expires_in = Date.now() + (data.expires_in - 300) * 1000;
                        data=JSON.stringify(data);
                        resolve(data);
                        await writeFile(path, data, err => {
                            if (!err) {
                                console.log('保存文件成功');
                            } else {
                                reject('保存文件出错' + err);
                            }
                        })
                    }else{
                        resolve(tt.ticket);
                    }
                } else {
                    reject('readAccessToken 出错' + err);
                }
            });

         

        });
    }

}
module.exports=Wechat;


// (async function () {
//     const w = new Wechat();
//      const q= await w.getJsTicket();
//      console.log(q)

//   })()
// (async function () {
//     const w = new Wechat();
//    await w.deleteMenu();
//    const aa= await w.createMenu(menu);
//     console.log(aa)

//   })()